package com.example.oasystem.controller.note;


import com.example.oasystem.config.ConstantProperties;
import com.example.oasystem.dao.attachment.AoaAttachmentListDaoOfJian;
import com.example.oasystem.dao.note.AoaNoteListDao;
import com.example.oasystem.dao.process.AoaProcessListDaoOfChen;
import com.example.oasystem.entity.attachment.AoaAttachmentListOfJian;
import com.example.oasystem.entity.daymanage.EmpDTO;
import com.example.oasystem.entity.file.AoaFileList;
import com.example.oasystem.entity.note.AoaCatalog;
import com.example.oasystem.entity.note.AoaNoteList;
import com.example.oasystem.entity.note.AoaReceiverNote;
import com.example.oasystem.entity.page.Page;
import com.example.oasystem.entity.process.AoaAttachmentList;
import com.example.oasystem.entity.status.AoaStatusList;
import com.example.oasystem.entity.type.AoaTypeList;
import com.example.oasystem.entity.user.AoaUser;
import com.example.oasystem.service.impl.noteServiceImpl;
import com.example.oasystem.utils.AliyunOSSUtil;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class NoteController {
    @Autowired
    private ConstantProperties constantProperties;
    @Autowired
    AoaNoteListDao noteListDao;
    @Autowired
    noteServiceImpl noteService;
    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;
    @Autowired
    private AoaAttachmentListDaoOfJian aoaAttachmentListDaoOfJian;
    @Autowired
    AoaProcessListDaoOfChen processListDaoOfChen;


    public void getNote(Long id, int cid, int typeId, Model model, HttpSession session, int pageNum, int pageSize) {
        PageInfo<AoaNoteList> alls = noteService.getNoteListLimit(Math.toIntExact(id),cid,typeId,pageNum,pageSize);
        List<AoaNoteList> noteLists = alls.getList();

        Page page=new Page(alls.getSize(), Math.toIntExact(alls.getTotal()),alls.getPages(),alls.getPageNum(),alls.isIsFirstPage(),alls.isIsLastPage());
        model.addAttribute("page", page);
        model.addAttribute("nlist", noteLists);
        model.addAttribute("url", "getNote");
        model.addAttribute("cid",cid);
        model.addAttribute("typeId",typeId);

    }
    private void get(Model model,HttpSession session){
        AoaUser user = (AoaUser) session.getAttribute("user");
        //查出所有的目录集合
        List<AoaCatalog> catalogs = noteListDao.catalogList(user.getUserId());
        //类型
        List<AoaTypeList> type = noteListDao.findType();

        //状态
        List<AoaStatusList> status = noteListDao.findStatus();

        model.addAttribute("statuslist",status);
        model.addAttribute("calist",catalogs);
        model.addAttribute("typelist",type);
    }
    public void findByText(int id,int cid,int typeId,String val, Model model, int pageNum, int pageSize) {

        PageInfo<AoaNoteList> alls = noteService.getNoteListLimitByText(id,cid,typeId,pageNum,pageSize,val);
        List<AoaNoteList> notelist = alls.getList();
        Page page=new Page(alls.getSize(), Math.toIntExact(alls.getTotal()),alls.getPages(),alls.getPageNum(),alls.isIsFirstPage(),alls.isIsLastPage());
        model.addAttribute("text", val);
        model.addAttribute("cid",cid);
        model.addAttribute("page", page);
        model.addAttribute("nlist", notelist);
        model.addAttribute("url", "getNote");
        model.addAttribute("typeId",typeId);
    }

    //笔记展示页面
    @RequestMapping("/noteview")
    public String noteview(Model model, HttpSession session,
                           @RequestParam(value = "cid",defaultValue = "0")int cid,
                           @RequestParam(value = "typeId",defaultValue = "0")int typeId,
                           @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                           @RequestParam(value = "pageSize",defaultValue = "10")int pageSize){
        AoaUser user = (AoaUser) session.getAttribute("user");
        getNote(user.getUserId(),cid,typeId,model,session,pageNum,pageSize);
        get(model,session);
        model.addAttribute("cid",cid);
        return "note/noteview";
    }
    @RequestMapping("getNote")
    public String index(Model model, HttpSession session,
                        @RequestParam(value = "cid",defaultValue = "0")int cid,
                        @RequestParam(value = "typeId",defaultValue = "0")int typeId,
                        @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                        @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                        @RequestParam(value = "baseKey", defaultValue = "") String baseKey) {
        AoaUser user = (AoaUser) session.getAttribute("user");
        if ("".equals(baseKey) || baseKey == null) {
            model.addAttribute("baseKey", baseKey);
            model.addAttribute("cid",cid);
            getNote(user.getUserId(),cid,typeId,model, session, pageNum, pageSize);
            get(model,session);
        } else {
            session.setAttribute("baseKey", baseKey);
            model.addAttribute("cid",cid);
            findByText(Math.toIntExact(user.getUserId()),cid,typeId,baseKey, model, pageNum, pageSize);
            get(model,session);
        }

        return "note/notewrite";
    }

    @RequestMapping("/notecata")
    public String notecata(@RequestParam(value = "id",defaultValue = "0")int cid,
                           HttpSession session,Model model,
                           @RequestParam(value = "typeId",defaultValue = "0")int typeId,
                           @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10") int pageSize
    ){
        if (cid == -2){
            cid = 0;
        }
        AoaUser user = (AoaUser) session.getAttribute("user");
        getNote(user.getUserId(),cid,typeId,model,session,pageNum,pageSize);
        get(model,session);
        model.addAttribute("cid",cid);
        return "note/notewrite";
    }
    //新增与修改页面
    @RequestMapping("/noteedit")
    public String noteedit(@RequestParam(value = "id",defaultValue = "0")int id,
                           @RequestParam(value = "cataid",defaultValue = "0")int cid,
                           Model model,HttpSession session){

        get(model,session);
        List<EmpDTO> allEmps = noteListDao.getAllEmps();
        System.out.println("id = " + id);
        int noteid=id;
        //根据id将整个note对象查找出来
        if (id!=-1&&id!=0)
        {
            AoaNoteList noteList = noteListDao.selectOneOfNote(noteid);
            if (noteList != null){
                model.addAttribute("note",noteList);
            }
        }
        /*if (cid !=0){
            //将目录对象查出来
            AoaCatalog catalog = noteListDao.selectOneCatalog(cid);
            model.addAttribute("catalog",catalog);
        }*/

        model.addAttribute("emplist",allEmps);
        model.addAttribute("id",id);
        model.addAttribute("cid",cid);

        return "note/noteedit";
    }
    @RequestMapping("/notewrite")
    public String notewrite(@RequestParam("id")int id){

        return "redirect:notecata";
    }

    public String uploadFile(MultipartFile filePath, String uploadUrl) {
        try {
            if(null != filePath){
                String filename = filePath.getOriginalFilename();
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(filePath.getBytes());
                    os.close();
                    filePath.transferTo(newFile);
                    //上传到OSS
                    uploadUrl = constantProperties.getHead() + aliyunOSSUtil.upload(newFile) + constantProperties.getEnd();
                }
            }
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        return uploadUrl;
    }

    @RequestMapping("/notesave")
    public String notesave(AoaNoteList noteList, MultipartFile filePath, AoaReceiverNote receiverNote,
                           @RequestParam(value = "id",defaultValue = "0")int id, HttpSession session){
        AoaUser user = (AoaUser) session.getAttribute("user");
        System.out.println("==="+id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (id==-1||id==0){
            System.out.println("进入新增");
            AoaAttachmentListOfJian aoaAttachmentListOfJian = new AoaAttachmentListOfJian();
            if (filePath!=null)
            {
                System.out.println("有文件"+filePath);

                String uploadUrl =null;
                uploadUrl = uploadFile(filePath, uploadUrl);
                aoaAttachmentListOfJian.setAttachmentPath(uploadUrl);
                String s = uploadUrl.split("\\?")[0];
                int beginIndex = s.lastIndexOf("/");
                String attachmentName = s.substring(beginIndex+1);
                String attachmentShuffix = attachmentName.split("\\.")[1];
                aoaAttachmentListOfJian.setModel("note");
                aoaAttachmentListOfJian.setUserId(user.getUserId()+"");
                aoaAttachmentListOfJian.setUploadTime(sdf.format(new Date()));
                aoaAttachmentListOfJian.setAttachmentShuffix(attachmentShuffix);
                aoaAttachmentListOfJian.setAttachmentName(attachmentName);
                aoaAttachmentListOfJian.setAttachmentType("image/"+attachmentShuffix);
                aoaAttachmentListOfJian.setAttachmentSize(filePath.getSize()+"");
                aoaAttachmentListDaoOfJian.insert(aoaAttachmentListOfJian);
                System.out.println("aoaAttachmentListOfJian = " + aoaAttachmentListOfJian);
            }
            noteList.setCreateTime(sdf.format(new Date()));
            noteList.setAttachId(aoaAttachmentListOfJian.getAttachmentId());
            noteList.setIsCollected(0L);
            noteList.setCreatemanId(user.getUserId());
            noteListDao.insertNote(noteList);
            //下面是插入关系表
            receiverNote.setUserId(Math.toIntExact(user.getUserId()));
            receiverNote.setNoteId(Math.toIntExact(noteList.getNoteId()));
            noteListDao.insertReceiveNote(receiverNote);
            if (!"".equals(noteList.getReceiver())){
                insertReceiverNote(noteList);
            }



        }else {
           //这里是修改
            AoaNoteList noteListById = noteListDao.selectOneOfNote(id);
            AoaAttachmentListOfJian aoaAttachmentListOfJian = new AoaAttachmentListOfJian();


            if (filePath!=null&&filePath.getSize()!=0)
            {
                System.out.println("有文件"+filePath);
                String uploadUrl =null;
                uploadUrl = uploadFile(filePath, uploadUrl);
                aoaAttachmentListOfJian.setAttachmentPath(uploadUrl);
                String s = uploadUrl.split("\\?")[0];
                int beginIndex = s.lastIndexOf("/");
                String attachmentName = s.substring(beginIndex+1);
                String attachmentShuffix = attachmentName.split("\\.")[1];
                aoaAttachmentListOfJian.setModel("note");
                aoaAttachmentListOfJian.setUserId(user.getUserId()+"");
                aoaAttachmentListOfJian.setUploadTime(sdf.format(new Date()));
                aoaAttachmentListOfJian.setAttachmentShuffix(attachmentShuffix);
                aoaAttachmentListOfJian.setAttachmentName(attachmentName);
                aoaAttachmentListOfJian.setAttachmentType("image/"+attachmentShuffix);
                aoaAttachmentListOfJian.setAttachmentSize(filePath.getSize()+"");
                aoaAttachmentListDaoOfJian.insert(aoaAttachmentListOfJian);
                System.out.println("aoaAttachmentListOfJian = " + aoaAttachmentListOfJian);
            }else {
                noteList.setAttachId(noteListById.getAttachId());
            }


            noteList.setCreatemanId(user.getUserId());
            noteList.setNoteId(Long.valueOf(id));
            System.out.println("88"+noteList);
            noteListDao.updateNoteList(noteList);

            //插入分享人的记录
            if (!"".equals(noteList.getReceiver())){
                noteListDao.deletReceiverNote(noteList.getNoteId());
                insertReceiverNote(noteList);
                AoaReceiverNote note=new AoaReceiverNote();
                note.setNoteId(Math.toIntExact(noteList.getNoteId()));
                note.setUserId(Math.toIntExact(user.getUserId()));
                noteListDao.insertReceiveNote(note);
            }

        }

        return "redirect:noteview";
    }

    //插入分享者的记录
    private void insertReceiverNote(AoaNoteList noteList){
        String[] receiverName = noteList.getReceiver().split(";");
        //创建user数组
        AoaUser[] users = new AoaUser[receiverName.length];
        for (int i = 0;i<receiverName.length;i++){
            //根据名字查找出user存起来
            users[i] = noteListDao.selectOneOfUser(receiverName[i]);
            AoaReceiverNote receiverNote = new AoaReceiverNote();
            receiverNote.setUserId(Math.toIntExact(users[i].getUserId()));
            receiverNote.setNoteId(Math.toIntExact(noteList.getNoteId()));
            System.out.println(receiverNote);
            noteListDao.insertReceiveNote(receiverNote);
        }
    }

    //查看
    @RequestMapping("/noteinfo")
    public String noteinfo(@Param("id")int id, Model model){
        AoaNoteList noteList = noteListDao.selectOneOfNote(id);
        AoaUser user = noteListDao.selectOneOfUserId(noteList.getCreatemanId());

        if (noteList.getAttachId()!=null){
            AoaAttachmentList attachmentList = noteListDao.selectOneAttach(noteList.getAttachId());
            model.addAttribute("att",attachmentList);
        }
        model.addAttribute("note",noteList);
        model.addAttribute("user",user);
        return "note/noteinfo";
    }

    @ResponseBody
    @RequestMapping("/downImg")
    public String downImg(@RequestParam(value = "attrid",defaultValue = "0")int attrid,
                           HttpServletResponse response,
                           @RequestParam(value = "nid",defaultValue = "0")int nid){
        AoaAttachmentList attachmentList=null;
        //查看中下载
        if (attrid != 0){
            attachmentList = noteListDao.selectOneAttach(Long.valueOf(attrid));
        }
        //展示页面下载
        if (nid != 0){
            AoaNoteList noteList = noteListDao.selectOneOfNote(nid);
            attachmentList = noteListDao.selectOneAttach(noteList.getAttachId());
        }
        String str=attachmentList.getAttachmentPath();
        String path1=str.substring(48);
        String[] path2=path1.split("\\?");
        System.out.println(path2[0]);
        AliyunOSSUtil.download(path2[0],response);
        return "note/noteinfo";
    }

    //新增目录
    @RequestMapping("/noteIncrease")
    public String noteIncrease(@RequestParam(value = "name",defaultValue = "")String name,
                               HttpSession session){
        AoaUser user = (AoaUser) session.getAttribute("user");
        noteListDao.insertcatalog(name,1,user.getUserId());
        return "redirect:noteview";
    }

    @RequestMapping("/notetype")
    public String notetype(@RequestParam(value = "id",defaultValue = "0")int cid,
                           @RequestParam(value = "typeid",defaultValue = "0")int typeId,
                           @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                           Model model,HttpSession session){
        System.out.println("类型"+typeId);
        cid=0;
        AoaUser user = (AoaUser) session.getAttribute("user");
        getNote(user.getUserId(),cid,typeId,model,session,pageNum,pageSize);
        get(model,session);
        return "note/notewrite";
    }

    @RequestMapping("/notedelete")
    public String notedelete(@RequestParam(value = "nid",defaultValue = "0")int nid,Model model,HttpSession session){
        AoaUser user = (AoaUser) session.getAttribute("user");
        AoaNoteList noteList = noteListDao.selectOneOfNote(nid);
        System.out.println("nid"+nid);
        System.out.println("nid"+noteList);

        //删除receiver主表
        noteListDao.deleteByNoteId(nid);
        if (noteList.getAttachId()!=null){

            noteListDao.deleteAttach(noteList.getAttachId());
        }
        //删除附表
        noteListDao.deleteNoteList(nid);
        return "redirect:noteview";
    }

    @RequestMapping("/notesomedelete")
    public String notesomedelete(@RequestParam("sum")String sum){
        System.out.println(sum);
        String[] split = sum.split(";");
        for (int i = 0; i < split.length; i++) {
            AoaNoteList noteList = noteListDao.selectOneOfNote(Integer.parseInt(split[i]));
            //删除receivernote
            noteListDao.deleteByNoteId(Integer.parseInt(split[i]));
            //删除note
            noteListDao.deleteNoteByNoteId(Integer.parseInt(split[i]));
            //删除对应的附件
            System.out.println("99"+noteList);
            System.out.println(Integer.parseInt(split[i]));
            if (noteList.getAttachId()!=null){
                noteListDao.deleteAttach(noteList.getAttachId());
            }
        }
        return "redirect:notecata";
    }
    @RequestMapping("/catadelete")
    public String catadelete(@RequestParam(value = "cid",defaultValue = "0")int cid){
        //根据目录id，将所有note查出来
        List<AoaNoteList> byCid = noteListDao.findByCid(cid);

        //根据noteid查查出所有receivernote
        //删除receivernote
        for (AoaNoteList note :byCid) {
            noteListDao.deleteByNoteId(Math.toIntExact(note.getNoteId()));
            //删除对应的附件
            if (note.getAttachId() != null)
                noteListDao.deleteAttach(note.getAttachId());
        }

        //删除note
        noteListDao.deleteNoteByCid(cid);

        //删除目录
        noteListDao.deleteCatalog(cid);
        return "redirect:noteview";
    }
    @RequestMapping("/collect")
    public String collect(@RequestParam(value = "id",defaultValue = "0")int id,
                          @RequestParam(value = "iscollected",defaultValue = "0")int iscollected){
        System.out.println("id = " + id);
        System.out.println("iscollected = " + iscollected);
        noteListDao.updateIsCollect(id,iscollected);
        return "redirect:noteview";
    }

}
